package thread;

import java.util.Comparator;
import java.util.PriorityQueue;

// 描述一个任务
class MyTimerTask implements Comparable<MyTimerTask> {
    // 要有一个执行的任务
    private Runnable runnable;
    private long time;

    public MyTimerTask(Runnable runnable, long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }

    public long getTime() {
        return this.time;
    }

    public Runnable getRunnable() {
        return runnable;
    }
}

// 定时器
class MyTimer {
    // 使用数据结构， 保存所有的任务
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    private  Object locker = new Object();

    public void schedule(Runnable runnable, long delay) {
        synchronized (locker) {
            queue.offer(new MyTimerTask(runnable, delay));
            locker.notify();
        }
    }

    // 搞个扫描线程
    public MyTimer() {
        // 创建一个扫描线程
        Thread t = new Thread(() -> {
            // 扫描线程，不停的扫描队首元素，看是否到达时间
            while(true) {
                synchronized (locker) {
                    while(queue.isEmpty()) {
                        // 使用wait进行等待
                        try {
                            locker.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    MyTimerTask task = queue.peek();
                    long curTime = System.currentTimeMillis();
                    if (curTime >= task.getTime()) {
                        task.getRunnable().run();
                        queue.poll();
                    } else {
                        // 没到任务时间 不需要时时刻刻查看
                        try {
                            locker.wait(task.getTime() - curTime);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

        });
        t.start();
    }
}

public class demo19 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3000");
            }
        }, 3000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2000");
            }
        }, 2000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1000");
            }
        }, 1000);

        System.out.println("程序开始执行");
    }
}
